//
// server.c (Corrected)
//

// --- NECESSARY HEADERS ADDED ---
#include <stdio.h>      // For printf, perror
#include <stdlib.h>     // For exit, EXIT_FAILURE, free
#include <string.h>     // For strcmp, strlen
#include <unistd.h>     // For read, write, close
#include <sys/socket.h> // For socket, bind, listen, accept
#include <arpa/inet.h>  // For sockaddr_in, htons, INADDR_ANY

// --- PROJECT-SPECIFIC HEADERS ---
#include "../common/common.h"
#include "../lib/cJSON.h"
#include "../common/rpc_protocol.h"
#include "remote_functions.h"
// --------------------------------

// Define a function pointer type for RPC handlers for cleaner code.
typedef cJSON *(*RpcHandler)(const cJSON *, RpcErrorCode *);

// A map to associate method names with their handler functions.
typedef struct
{
  const char *method_name;
  RpcHandler handler;
} RpcMethodMap;

// The dispatch table. To add a new RPC method, just add an entry here.
// The list is terminated by a {NULL, NULL} entry (sentinel).
static const RpcMethodMap method_map[] = {
    {"add", remote_add},
    {"getUserInfo", remote_get_user_info},
    {"sumAndPrint", remote_sum_and_print},
    {"processUserProfile", remote_process_user_profile},
    {NULL, NULL}};

/**
 * @brief Finds the handler function for a given method name.
 * @param method_name The name of the method to find.
 * @return A function pointer to the handler, or NULL if not found.
 */
static RpcHandler find_handler(const char *method_name)
{
  for (int i = 0; method_map[i].method_name != NULL; ++i)
  {
    if (strcmp(method_map[i].method_name, method_name) == 0)
    {
      return method_map[i].handler;
    }
  }
  return NULL;
}

/**
 * @brief Handles a single client connection from start to finish.
 * @param client_sock The socket file descriptor for the connected client.
 */
static void handle_connection(int client_sock)
{
  char buffer[MAX_BUFFER_SIZE] = {0};
  char *response_str = NULL;

  // Note: ssize_t is defined in <unistd.h>
  ssize_t bytes_read = read(client_sock, buffer, sizeof(buffer) - 1);
  if (bytes_read <= 0)
  {
    if (bytes_read < 0)
    {
      perror("Read error");
    }
    else
    {
      printf("Client closed connection.\n");
    }
    close(client_sock);
    return;
  }
  buffer[bytes_read] = '\0';
  printf("Server: Received request:\n%s\n", buffer);

  cJSON *request_json = cJSON_Parse(buffer);
  if (request_json == NULL)
  {
    response_str = create_json_rpc_error_response(RPC_PARSE_ERROR, "Parse error", NULL);
  }
  else
  {
    cJSON *method_json = cJSON_GetObjectItem(request_json, "method");
    cJSON *params_json = cJSON_GetObjectItem(request_json, "params");
    cJSON *id_json = cJSON_GetObjectItem(request_json, "id");

    if (!cJSON_IsString(method_json) || !(cJSON_IsArray(params_json) || cJSON_IsObject(params_json)) || id_json == NULL)
    {
      response_str = create_json_rpc_error_response(RPC_INVALID_REQUEST, "Invalid Request", id_json);
    }
    else
    {
      RpcHandler handler = find_handler(method_json->valuestring);
      if (handler == NULL)
      {
        response_str = create_json_rpc_error_response(RPC_METHOD_NOT_FOUND, "Method not found", id_json);
      }
      else
      {
        RpcErrorCode error_code = RPC_SUCCESS;
        cJSON *result = handler(params_json, &error_code);
        if (error_code != RPC_SUCCESS)
        {
          response_str = create_json_rpc_error_response(error_code, "Invalid parameters", id_json);
          cJSON_Delete(result); // Clean up any partial results.
        }
        else
        {
          response_str = create_json_rpc_success_response(result, id_json);
        }
      }
    }
  }

  if (response_str != NULL)
  {
    printf("Server: Sending response:\n%s\n\n", response_str);
    write(client_sock, response_str, strlen(response_str));
    // MISRA Deviation: free() is required here to release memory allocated
    // by cJSON_PrintUnformatted or create_json_rpc_error_response.
    free(response_str);
  }

  cJSON_Delete(request_json);
  close(client_sock);
}

int main(void)
{
  int server_fd, new_socket;
  struct sockaddr_in address;
  int opt = 1;
  socklen_t addrlen = sizeof(address);

  if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
  {
    perror("socket failed");
    exit(EXIT_FAILURE);
  }

  if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)))
  {
    perror("setsockopt");
    exit(EXIT_FAILURE);
  }
  address.sin_family = AF_INET;
  address.sin_addr.s_addr = INADDR_ANY;
  address.sin_port = htons(SERVER_PORT);

  if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0)
  {
    perror("bind failed");
    exit(EXIT_FAILURE);
  }
  if (listen(server_fd, MAX_CONNECTIONS_QUEUE) < 0)
  {
    perror("listen");
    exit(EXIT_FAILURE);
  }

  printf("Server listening on port %d\n", SERVER_PORT);

  // Main server loop
  while (1)
  {
    if ((new_socket = accept(server_fd, (struct sockaddr *)&address, &addrlen)) < 0)
    {
      perror("accept");
      continue; // Continue to the next iteration on accept failure.
    }
    handle_connection(new_socket);
  }

  // This part is unreachable in this simple server design, but good practice.
  close(server_fd);
  return 0;
}
